﻿namespace Mercury.ParticleEngine
{
    using System;
    using System.Diagnostics.Contracts;

    /// <summary>
    /// Defines common extension methods for the <see cref="T:System.Int32"/> type.
    /// </summary>
    public static class Int32Extensions
    {
        /// <summary>
        /// Gets a value indicating whether or not the integer value is a perfect square.
        /// </summary>
        /// <param name="value">The extension instance.</param>
        /// <returns><c>true</c> if the integer value is a perfect square; else <c>false</c>.</returns>
        [Pure]
        static public Boolean IsPerfectSquare(this Int32 value)
        {
            var hex = value & 0xf;

            // We know that in hexadecimal square numbers always end in either 0, 1, 4 or 9, so we
            // only need to do the more complex square root evaluation in those circumstances...
            if (hex == 0 || hex == 1 | hex == 4 | hex == 9)
            {
                var t = (Int32)Math.Floor(Calculator.SquareRoot(value) + 0.5d);

                return t * t == value;
            }

            return false;
        }
    }
}